package leetcode.editor.cn;

import java.util.HashMap;
import java.util.Map;

public class _76_MinimumWindowSubstring {
    public static void main(String[] args) {
        Solution solution = new _76_MinimumWindowSubstring().new Solution();
        String s = solution.minWindow("ADOBECODEBANC", "ABC");
        System.out.println(s);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String minWindow(String s, String t) {
            int n = s.length();
            Map<Character, Integer> need = new HashMap<>();
            Map<Character, Integer> window = new HashMap<>();
            for (char c : t.toCharArray()) {
                need.put(c, need.getOrDefault(c, 0) + 1);
            }
            int left = 0, right = 0, valid = 0, start = 0, res = Integer.MAX_VALUE;
            while (right < n) {
                char c = s.charAt(right);
                right++;
                if (need.containsKey(c)) {
                    window.put(c, window.getOrDefault(c, 0) + 1);
                    if (window.get(c).equals(need.get(c))) {
                        valid++;
                    }
                }
                while (valid == need.size()) {
                    if (right - left < res) {
                        start = left;
                        res = right - left;
                    }
                    char d = s.charAt(left);
                    left++;
                    if (need.containsKey(d)) {
                        if (window.get(d).equals(need.get(d))) {
                            valid--;
                        }
                        window.put(d, window.get(d) - 1);
                    }
                }
            }
            return res == Integer.MAX_VALUE ? "" : s.substring(start, start + res);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}